
/** 
 * 手写 promise
 * promise分析
 *      1.promise是一个类，这个类通过构造函数来传递一个执行器，执行器来立即执行
 *      2.promise有3个状态，分别是：pending fulfilled rejected
 *           pending --> fulfilled pending --> rejected fulfilled 和 rejected 一旦确定就不能修改
 *      3.resolve reject 方法是用来改变状态
 *      4.then 方法用来判断状态，调用相应的回调函
 *          异步情况的处理( then方法中如果是 pending 状态时先将回调函数缓存，在 resolve/reject 调用前判断存在就调用)
 *          then方法多次异步调用的处理
 *          then方法的链式调用以及传递返回值
 *          then方法中返回值是 Promise 对象时的处理
 *          then方法中识别自返回对象的处理
 *      5.捕获错误then链式调用其他状态处理
 *      6.then方法参数变为可选参数
 *      7.promise.all方法实现:all 是一个静态方法，接收一个数组，返回Promise 对象
 *      8.promise.resolve方法实现:resolve是一个静态方法，返回一个 promise 对象
 *      9.实现 finally:无认 promise 最终是fulfilled还是 reject，finally都会被执行.finally 方法后面可以链式调用 then 方法(返回 promise 对象)
 *      10.实现 catch 方法
 */

const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise {
    constructor(executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (e) {
            this.reject(e)
        }
    }
    //初始状态
    status = PENDING
    //成功的值
    value = undefined
    //失败的原因
    reason = undefined
    //成功回调,用数组存储所有回调，因为每个回调都要被执行到
    successCallback = []
    // 失败回调数组
    failCallback = []

    resolve = value => {
        if (this.status !== PENDING) return
        this.status = FULFILLED
        this.value = value
        //判断成功回调是否存在，存在则调用
        // this.successCallback && this.successCallback(this.value)
        //需要将所有回调都执行到
        while (this.successCallback.length) this.successCallback.shift()()

    }
    reject = reason => {
        if (this.status !== PENDING) return
        this.status = REJECTED
        this.reason = reason
        //判断失败回调是否存在，存在则调用
        // this.failCallback && this.failCallback(this.reason)
        while (this.failCallback.length) this.failCallback.shift()(this.reason)
    }
    then = (successCallback, failCallback) => {
        successCallback = successCallback ? successCallback : value => value
        failCallback = failCallback ? failCallback : reason => { throw reason }
        //要实现链式调用，then 方法需要返回 promise 对象
        let promise = new MyPromise((resolve, reject) => {
            //状态的判断
            if (this.status === FULFILLED) {
                setTimeout(() => {
                    try {
                        let v = successCallback(this.value)
                        // resolve(v)
                        //判断返回值类型，做不同处理
                        //promise 在同步块中拿不到 promise 对象，所以要放到异步中去执行
                        resolvePromise(promise, v, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                }, 0);
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        let v = failCallback(this.reason)
                        // 
                        //判断返回值类型，做不同处理
                        //promise 在同步块中拿不到 promise 对象，所以要放到异步中去执行
                        resolvePromise(promise, v, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                }, 0);
            } else {
                //将回调函数放入数组
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let v = successCallback(this.value)
                            // resolve(v)
                            //判断返回值类型，做不同处理
                            //promise 在同步块中拿不到 promise 对象，所以要放到异步中去执行
                            resolvePromise(promise, v, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0);
                })
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let v = failCallback(this.reason)
                            // resolve(v)
                            //判断返回值类型，做不同处理
                            //promise 在同步块中拿不到 promise 对象，所以要放到异步中去执行
                            resolvePromise(promise, v, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0);
                })
            }
        });
        return promise;
    }

    finally(callback) {
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value)
        }, reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason })
        })
    }

    catch(failCallback) {
        return this.then(undefined, failCallback)
    }

    static all(array) {
        let result = []
        let count = 0
        return new MyPromise((resolve, reject) => {
            //循环数组执行数组中的调用，判断是 Promise 对象还是普通值
            for (let i = 0; i < array.length; i++) {
                let v = array[i]
                if (v instanceof MyPromise) {
                    v.then(value => { pushData(i, value) }, reason => reject(reason))
                } else {
                    pushData(i, v)
                }
            }
            function pushData(key, value) {
                result[key] = value
                count++
                if (count === array.length) resolve(result)
            }
        })
    }

    static resolve(v) {
        if (v instanceof MyPromise) {
            return v
        } else {
            return new MyPromise((resolve, reject) => {
                resolve(v)
            })
        }
    }
}

function resolvePromise(promise, v, resolve, reject) {
    if (promise === v) return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))

    if (v instanceof MyPromise) {
        v.then(resolve, reject)
    } else {
        resolve(v)
    }
}

module.exports = MyPromise